<template>
  <div>
    <div class="robot-list" id="container" @scroll="getRobotList">
      <div
        class="robot"
        v-for="(item, index) in robotlist"
        :key="index"
        @click="handleChoose(item)"
      >
        <div class="robot-img">
          <img :src="item.avatar | imageUrl" alt="" />
        </div>
        <div class="name-uid">
          <div class="name">{{ item.nickname }}</div>
          <div class="uid">{{ item.uid }}</div>
        </div>
      </div>
    </div>
    <IMApp v-if="uikitInit" />
  </div>
</template>

<script lang="ts">
import IMApp from './components/IMApp/index.vue'
import { IMUIKit, useStateContext } from '@xkit-yx/im-kit-ui'
import RootStore from '@xkit-yx/im-store'
import { NimKitCoreFactory, NimKitCoreTypes } from '@xkit-yx/core-kit'
import Vue from 'vue'
import { robotListApi, chatReportApi } from '@/api/whisper'

export default {
  name: 'communicate',
  components: {
    IMApp
  },
  data() {
    return {
      uikitInit: false,
      robotlist: [],
      // account: '59122690',
      // token: 'c7ebd0bc2d1d04594f4246f3e894b9d8',

      limit: 20,
      page: 1,
      isLoading: false,
      isEnd: false,
      contentText: {
        msg: ''
      },
      contentFile: {
        name: '',
        url: '',
        ext: '',
        w: '',
        h: '',
        messageType: 'image',
        force_upload: true
      }
    }
  },
  created() {},
  mounted() {
    document
      .getElementById('container')
      .addEventListener('scroll', this.getRobotList())
  },
  methods: {
    // 获取机器人列表
    getRobotList() {
      const params = {
        limit: this.limit,
        page: this.page
      }
      if (!this.isLoading && !this.isEnd) {
        this.isLoading = true
        robotListApi(params).then(res => {
          // console.log('机器人', res)
          this.isLoading = false
          if (res.status == 200) {
            if (res.data.list.length < this.limit) {
              this.isEnd = true
            } else {
              this.robotlist = this.robotlist.concat(res.data && res.data.list)
              this.page++
              if (this.robotlist) {
                this.initialize()
              }
            }
          }
        })
      }
    },

    // 按钮
    logout() {
      // 重新渲染 uikit 页面
      this.uikitInit = false
      // 手动释放 uikit 实例内存
      window.__xkit_store__.store.destroy()
      window.__xkit_store__.nim.destroy()
      // 这里根据 sdkVersion 传入 1 或 2
      const NIM = NimKitCoreFactory(1)
      RootStore.ins = undefined
      NIM.ins = undefined
    },

    // 切换选择
    handleChoose(val) {
      this.logout()
      setTimeout(() => {
        this.initialize(val.uid, val.imToken)
      }, 2000)
    },

    // 初始化
    initialize(uid, imToken) {
      this.uikitInit = false
      const initOptions = {
        appkey:
          process.env.NODE_ENV === 'production'
            ? 'a8ddbe33fe3edda91dd63eb82db84147'
            : '1b519fb7bebc4ab8b5c3c8ea21098d9c',
        account: uid || this.robotlist[0].uid,
        token: imToken || this.robotlist[0].imToken
      }
      const localOptions = {
        // 添加好友模式，默认需要验证
        addFriendNeedVerify: false,
        // 群组被邀请模式，默认不需要验证
        // teamBeInviteMode: 'noVerify' as 'noVerify' | 'needVerify',
        // 单聊消息是否显示已读未读 默认 false
        p2pMsgReceiptVisible: false,
        // 群聊消息是否显示已读未读 默认 false
        teamMsgReceiptVisible: true,
        // 是否需要@消息 默认 true
        needMention: true,
        // 是否显示在线离线状态 默认 true
        loginStateVisible: true,
        // 是否允许转让群主
        allowTransferTeamOwner: true,
        sendMsgBefore: options => {
          options = {
            ...options
          }
          return options
        }
      }

      const funcOptions = {
        onupdatesession: obj => {
          console.log('obj--------', obj)
          let id = uid || this.robotlist[0].uid
          this.chatReport(obj, id)
        }
      }
      const otherOptions = {
        lbsUrl: 'https://lbs.netease.im/lbs/webconf',
        defaultLink: 'weblink01-sg.netease.im:443',
        httpsEnabled: true
      }

      Vue.prototype.$uikit = new IMUIKit({
        initOptions,
        singleton: true,
        sdkVersion: 1,
        localOptions,
        funcOptions,
        otherOptions
      })

      if (Vue.prototype.$uikit) {
        this.uikitInit = true
      }
    },

    chatReport(obj, robotUid) {
      if (obj.lastMsg.file) {
        let data = obj.lastMsg.file
        this.contentFile.name = data.name
        this.contentFile.url = data.url
        this.contentFile.ext = data.ext
        this.contentFile.w = data.w
        this.contentFile.h = data.h
      } else {
        this.contentText.msg = obj.lastMsg.text
      }
      const data = {
        chatUid: obj.lastMsg.target,
        // content: obj.lastMsg.text,
        content: obj.lastMsg.file
          ? JSON.stringify(this.contentFile)
          : JSON.stringify(this.contentText),
        msgType: obj.lastMsg.file ? 1 : 0,
        recordMatchKey: obj.lastMsg.idServer + '_p2p',
        uid: obj.lastMsg.from
      }
      if (robotUid == obj.lastMsg.from) {
        if (obj.lastMsg.idServer) {
          chatReportApi(data).then(res => {
            // console.log('请求成功', res)
          })
        }
      }
    }
  }
}
</script>
<style scoped lang="scss">
.robot-list {
  width: 200px;
  height: calc(100vh - 200px);
  margin: 20px 0 0 10px;
  overflow: scroll;
  border-radius: 8px;
  box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.6);
  .robot {
    display: flex;
    align-items: center;
    margin: 10px 0;
    padding: 0 15px;
    cursor: pointer;
    transition: all 0.5s;
    .robot-img {
      width: 40px;
      height: 40px;
      margin-right: 10px;
      overflow: hidden;
      border-radius: 50%;

      > img {
        display: block;
        width: 100%;
        height: 100%;
        border-radius: 50%;
        object-fit: cover;
      }
    }
    .name-uid {
      display: flex;
      flex-direction: column;
      align-content: center;
      color: #000;
      font-size: 16px;
    }
    .name {
      font-weight: 600;
    }
  }
  .robot:hover .name-uid {
    color: #1890ff;
  }
  .robot:hover {
    box-shadow: 0px 2px 10px 0px rgba(0, 0, 0, 0.6);
  }
  .robot:hover .robot-img {
    > img {
      transform: scale(1.2);
    }
  }
}

.robot-list::-webkit-scrollbar {
  width: 3px;
}
.robot-list::-webkit-scrollbar-thumb {
  background: #8eadca;
  border-radius: 10px;
}
.robot-list::-webkit-scrollbar-track-piece {
  background: transparent;
}
</style>
